<?php
class Dictionary_Manager
{
	static protected $_instance = null;
	
	static protected $_cacheKey = 'Dictionary_Manager_list';
	
	protected $_path ='';
	/**
	 * @var Zend_Cache_Core
	 */
	protected $_cache = false;
	
	protected $_list = null;
	
	protected function __clone(){}
	
	/**
	 * @return Dictionary_Manager
	 */
	static public function getInstance()
	{
		if(is_null(self::$_instance))
			self::$_instance = new self;
		return self::$_instance;	
	}
	
	protected function __construct()
	{
		$this->_path = Application::getConfig()->get('dictionary');
		$this->_cache = Application::dataCache();
				
		if($this->_cache && $list = $this->_cache->load(self::$_cacheKey))
			$this->_list = $list;
	}
	
	/**
	 * Get list of dictionaries
	 * return array
	 */
	public function getList()
	{
		if(!is_null($this->_list))
			return array_keys($this->_list);
					
		$files = File::scanFiles($this->_path, array('.php'), false, File::Files_Only);
		$list = array();
		
		if(empty($files)){
			$this->_list = array();
			return array();
		}

		foreach($files as $path){
			$name = substr(basename($path),0,-4);
			$list[$name] = $path;
		}

		if($this->_cache)
			$this->_cache->save($list, self::$_cacheKey);
			
		return array_keys($list);
	}
	/**
	 * Create dictionary
	 * @param string $name
	 * @return boolean
	 */
	public function create($name){
		return Config_File_Array::create($this->_path.$name.'.php');
	}
	/**
	 * Rename dictionary
	 * @param string $oldName
	 * @param string $newName
	 * @return boolean
	 */
	public function rename($oldName, $newName) {
		if(!@rename($this->_path.$oldName.'.php', $this->_path.$newName.'.php'))
			return false;
		if($this->_cache)
			$this->_cache->remove(self::$_cacheKey);
		return true;	
	}
	/**
	 * Remove dictionary
	 * @param string $name
	 * @return boolean
	 */
	public function remove($name){
		$file = $this->_path.$name.'.php';
		if(!is_file($file) || !@unlink($file))
			return false;
			
		if($this->_cache)
			$this->_cache->remove(self::$_cacheKey);
			
		return true;
	}
}